package com.xjcs.saplingplan

import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.jeremyliao.liveeventbus.LiveEventBus
import com.umeng.commonsdk.UMConfigure
import com.xjcs.saplingplan.base.BaseVbActivity
import com.xjcs.saplingplan.const.AppConfigConst
import com.xjcs.saplingplan.const.AppMainTab
import com.xjcs.saplingplan.const.EventBusConstants
import com.xjcs.saplingplan.const.createIconWithNumber
import com.xjcs.saplingplan.const.getMainTabIcon
import com.xjcs.saplingplan.databinding.ActivityMainBinding
import com.xjcs.saplingplan.datastore.AppData
import com.xjcs.saplingplan.ui.fragment.CountdownFragment
import com.xjcs.saplingplan.ui.fragment.FocusFragment
import com.xjcs.saplingplan.ui.fragment.MemoFragment
import com.xjcs.saplingplan.ui.fragment.MineFragment
import com.xjcs.saplingplan.ui.fragment.PlanFragment
import com.xjcs.saplingplan.ui.fragment.StatisticsFragment
import com.xjcs.saplingplan.ui.fragment.ViewFragment
import com.xjcs.saplingplan.ui.viewmodel.AppViewModel
import kotlinx.coroutines.launch
import java.util.Calendar

class MainActivity : BaseVbActivity<ActivityMainBinding>() {

    private val appViewModel: AppViewModel by viewModels()

    private var currentTab: AppMainTab? = null
    private val fragmentMap: MutableMap<AppMainTab, Fragment?> = mutableMapOf()
    private var isInitialized = false

    private val userId = AppData.getUserId()
    private val userInfoBean = AppData.getUserInfo()

    override fun getViewBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun initUi(savedInstanceState: Bundle?) {
        // 处理可能的Intent数据
        doIntent(intent)
        initTabSystem()
        UMConfigure.init(this, AppConfigConst.UM_APP_KEY, BuildConfig.FLAVOR, UMConfigure.DEVICE_TYPE_PHONE, "")
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        intent.let {
            setIntent(it)
            doIntent(it)
        }
    }

    private fun initTabSystem() {
        if (isInitialized) return
        //初始化Tab
        refreshTabConfig()
        isInitialized = true
    }

    private fun doIntent(intent: Intent) {
        when (intent.action) {
            //直接跳转到特定Tab
            "JUMP_TO_TAB" -> {
                val tabName = intent.getStringExtra("TAB_NAME")
                tabName?.let { jumpToTab(it) }
            }
        }
    }

    private fun jumpToTab(tabName: String) {
        val targetTab = AppMainTab.entries.find { it.name.equals(tabName, true) }
        targetTab?.let { tab ->
            val selectedTabs = AppMainTab.entries.toTypedArray()
            if (selectedTabs.contains(tab)) {
                val position = selectedTabs.indexOf(tab)
                mBinding.bottomNavigation.selectedItemId = position
                switchFragment(tab)
            }
        }
    }

    private fun refreshTabConfig() {
        appViewModel.getAppMainTab(userId)
    }

    override fun registerObserver() {
        LiveEventBus.get<String>(EventBusConstants.REFRESH_MAIN_TAB).observe(this) {
            initTabSystem()
        }

        lifecycleScope.launch {
            appViewModel.appTabState.collect {
                setupBottomNavigation(it)
            }
        }
    }

    override fun initListener() {
    }

    private fun setupBottomNavigation(selectTabs: List<AppMainTab>) {
        //清除现有配置
        mBinding.bottomNavigation.menu.clear()
        fragmentMap.clear()

        //创建新的Tab和Fragment
        selectTabs.forEachIndexed { index, tabType ->
            mBinding.bottomNavigation.menu.add(0, index, index, tabType.desc).apply {
                if (tabType == AppMainTab.VIEW) {
                    val dayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
                    val icon = getMainTabIcon(tabType)
                    createIconWithNumber(this@MainActivity, icon, dayOfMonth)
                    //可配置图标
                    setIcon(icon)
                } else {
                    //可配置图标
                    setIcon(getMainTabIcon(tabType))
                }
            }
            fragmentMap[tabType] = createFragmentByType(tabType)

//            setBottomTabColors()
        }

        //默认选中第一个Tab
        if (selectTabs.isNotEmpty()) {
            mBinding.bottomNavigation.selectedItemId = 0
            switchFragment(selectTabs[0])
        }

        mBinding.bottomNavigation.setOnItemSelectedListener { item ->
            // 获取当前选中的菜单项视图
            val menuItemView = mBinding.bottomNavigation.findViewById<View>(item.itemId)
            val tabIndex = item.itemId
            // 缩放动画（按下缩小，松开恢复）
            menuItemView.animate()
                .scaleX(1.1f)
                .scaleY(1.1f)
                .setDuration(100)
                .withEndAction {
                    menuItemView.animate()
                        .scaleX(1f)
                        .scaleY(1f)
                        .setDuration(100)
                        .start()
                }
                .start()
            if (tabIndex in selectTabs.indices) {
                switchFragment(selectTabs[tabIndex])
                true
            } else {
                false
            }
        }

    }

    /**
     * 动态设置tab选中颜色
     */
    private fun setBottomTabColors() {
        // 动态设置颜色选择器
        val iconColorStates = ColorStateList(
            arrayOf(
                intArrayOf(android.R.attr.state_checked), // 选中状态
                intArrayOf(-android.R.attr.state_checked) // 未选中状态
            ),
            intArrayOf(
                R.color.color_34C759, // 选中色
                Color.BLACK // 未选中色
            )
        )
        mBinding.bottomNavigation.itemIconTintList = iconColorStates
        mBinding.bottomNavigation.itemTextColor = iconColorStates // 可单独设置文字颜色
    }

    private fun createFragmentByType(tabType: AppMainTab): Fragment {
        return when (tabType) {
            AppMainTab.INVENTORY -> PlanFragment()
            AppMainTab.VIEW -> ViewFragment()
            AppMainTab.FOCUS -> FocusFragment()
            AppMainTab.COUNTDOWN -> CountdownFragment()
            AppMainTab.STATISTICS -> StatisticsFragment()
            AppMainTab.MEMO -> MemoFragment()
            AppMainTab.MINE -> MineFragment()
        }
    }

    private fun switchFragment(tabType: AppMainTab) {
        if (currentTab == tabType) return

        val fragment = fragmentMap[tabType] ?: return
        val transaction = supportFragmentManager.beginTransaction()

        currentTab?.let {
            fragmentMap[it]?.let { currentFragment ->
                transaction.hide(currentFragment)
            }
        }

        if (fragment.isAdded) {
            transaction.show(fragment)
        } else {
            transaction.add(R.id.fragment, fragment, tabType.name)
        }
        transaction.commit()
        currentTab = tabType
    }

    override fun onDestroy() {
        super.onDestroy()
    }

}